// pages/goods/index.js
Page({
  data: {
    contractId: '', // 合同ID
    flow: 'landlord', // 流程类型
    contractData: {}, // 合同数据
    // 物品列表，默认全选
    goodsList: [
      { id: 1, name: '微波炉', checked: true },
      { id: 2, name: '投影仪', checked: true },
      { id: 3, name: '书桌', checked: true },
      { id: 4, name: '椅子', checked: true },
      { id: 5, name: '床', checked: true },
      { id: 6, name: '衣柜', checked: true },
      { id: 7, name: '沙发', checked: true },
      { id: 8, name: '电视', checked: true },
      { id: 9, name: '冰箱', checked: true },
      { id: 10, name: '洗衣机', checked: true },
      { id: 11, name: '空调', checked: true },
      { id: 12, name: '热水器', checked: true },
      { id: 13, name: '茶几', checked: true },
      { id: 14, name: '餐桌', checked: true },
      { id: 15, name: '窗帘', checked: true },
      { id: 16, name: '灯具', checked: true }
    ],
    showResult: false // 是否显示结果页面
  },

  async onLoad(options) {
    // 记录流程类型
    const flow = options.flow || 'landlord';
    this.setData({ flow: flow });
    
    // 如果是租客流程，通过合同ID加载
    if (flow === 'tenant' && options.contractId) {
      this.setData({ contractId: options.contractId });
      await this.loadContractData();
    } else if (options.data) {
      // 房东流程，接收合同数据
      try {
        const contractData = JSON.parse(decodeURIComponent(options.data));
        this.setData({
          contractData: contractData
        });
        console.log('合同数据已加载:', contractData);
      } catch (e) {
        console.error('解析合同数据失败:', e);
        wx.showToast({
          title: '数据加载失败',
          icon: 'none'
        });
      }
    }
  },
  
  // 加载合同数据（租客流程）
  async loadContractData() {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    
    try {
      const res = await wx.cloud.callFunction({
        name: 'contract',
        data: {
          apiType: 'getContractInfo',
          contractId: this.data.contractId
        }
      });

      wx.hideLoading();

      if (res.result.res.code === 200) {
        const contractData = res.result.res.data;
        this.setData({
          contractData: contractData
        });
        
        // 如果有物品列表，恢复选中状态
        if (contractData.goods && Array.isArray(contractData.goods)) {
          const goodsList = this.data.goodsList;
          goodsList.forEach(item => {
            item.checked = contractData.goods.includes(item.name);
          });
          this.setData({ goodsList: goodsList });
        }
        
        console.log('合同数据已加载:', contractData);
      } else {
        wx.showToast({
          title: res.result.res.msg || '加载失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('加载合同数据失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      });
    }
  },

  // 切换物品选中状态
  onGoodsChange(e) {
    const checkedValues = e.detail.value;
    const goodsList = this.data.goodsList;
    
    // 更新所有物品的选中状态
    goodsList.forEach(item => {
      item.checked = checkedValues.includes(item.name);
    });
    
    this.setData({
      goodsList: goodsList
    });
    
    // 如果是租客流程，自动保存
    if (this.data.flow === 'tenant' && this.data.contractId) {
      this.saveGoods();
    }
  },
  
  // 保存物品列表（租客流程）
  async saveGoods() {
    if (!this.data.contractId) {
      return;
    }
    
    const selectedGoods = this.data.goodsList.filter(item => item.checked).map(item => item.name);
    
    try {
      await wx.cloud.callFunction({
        name: 'contract',
        data: {
          apiType: 'updateContractGoods',
          contractId: this.data.contractId,
          goods: selectedGoods
        }
      });
    } catch (error) {
      console.error('保存物品失败:', error);
    }
  },

  // 确认发起签约（房东流程）或下一步（租客流程）
  async confirmContract() {
    const { flow, contractId, contractData } = this.data;
    
    // 如果是租客流程，保存物品后跳转到签名页面
    if (flow === 'tenant' && contractId) {
      await this.saveGoods();
      wx.showToast({
        title: '已保存',
        icon: 'success'
      });
      setTimeout(() => {
        wx.navigateTo({
          url: `/pages/signature/index?contractId=${contractId}&flow=tenant`
        });
      }, 500);
      return;
    }
    
    // 房东流程，继续原有逻辑
    // 验证必要数据
    if (!contractData.roomId) {
      wx.showToast({
        title: '房间信息缺失',
        icon: 'none'
      });
      return;
    }

    // 获取选中的物品
    const selectedGoods = this.data.goodsList.filter(item => item.checked).map(item => item.name);
    
    // 显示加载提示
    wx.showLoading({
      title: '正在创建合同...',
      mask: true
    });

    try {
      // 调用云函数创建合同
      const res = await wx.cloud.callFunction({
        name: 'contract',
        data: {
          apiType: 'addContract',
          roomId: contractData.roomId,
          // 甲方（房东）信息
          landlordName: contractData.landlordName || '未填写',
          landlordPhone: contractData.landlordPhone || '未填写',
          landlordIdCard: contractData.landlordIdCard || '未填写',
          landlordAddress: contractData.landlordAddress || '未填写',
          // 乙方（承租人）信息（可选）
          tenantName: contractData.tenantName || '',
          tenantPhone: contractData.tenantPhone || '',
          tenantIdCard: contractData.tenantIdCard || '',
          tenantAddress: contractData.tenantAddress || '',
          // 租赁期限（可选）
          startYear: contractData.startYear || '',
          startMonth: contractData.startMonth || '',
          startDay: contractData.startDay || '',
          endYear: contractData.endYear || '',
          endMonth: contractData.endMonth || '',
          endDay: contractData.endDay || '',
          renewNoticeMonths: contractData.renewNoticeMonths || '1',
          // 租金信息
          monthlyRent: contractData.monthlyRent || '',
          monthlyRentUpper: contractData.monthlyRentUpper || '',
          paymentMethod: contractData.paymentMethod || '',
          paymentDaysBefore: contractData.paymentDaysBefore || '3',
          lateFeePercent: contractData.lateFeePercent || '5',
          // 押金信息
          deposit: contractData.deposit || '',
          depositUpper: contractData.depositUpper || '',
          // 物业费
          propertyFee: contractData.propertyFee || '',
          // 交付日期
          deliveryYear: contractData.deliveryYear || '',
          deliveryMonth: contractData.deliveryMonth || '',
          deliveryDay: contractData.deliveryDay || '',
          // 合同解除相关
          overdueDays: contractData.overdueDays || '15',
          overdueAmount: contractData.overdueAmount || '1000',
          // 违约责任
          penaltyAmount: contractData.penaltyAmount || '2000',
          penaltyAmountUpper: contractData.penaltyAmountUpper || '',
          // 物品清单
          goods: selectedGoods
        }
      });

      if (res.result.res.code === 200) {
        const contractId = res.result.res.data._id;
        
        this.setData({
          contractId: contractId,
          showResult: true
        });

        try {
          await wx.cloud.callFunction({
            name: 'contract',
            data: {
              apiType: 'markContractCreated',
              contractId: contractId
            }
          });
        } catch (markError) {
          console.error('标记合同状态失败:', markError);
        }

        wx.hideLoading();
        wx.showToast({
          title: '合同创建成功',
          icon: 'success'
        });
      } else {
        throw new Error(res.result.res.msg || '创建合同失败');
      }
    } catch (error) {
      console.error('创建合同失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: error.message || '创建合同失败，请重试',
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 复制合同ID
  copyContractId() {
    if (!this.data.contractId) {
      wx.showToast({
        title: '合同ID不存在',
        icon: 'none'
      });
      return;
    }
    wx.setClipboardData({
      data: this.data.contractId,
      success: () => {
        wx.showToast({
          title: '合同ID已复制',
          icon: 'success'
        });
      },
      fail: () => {
        wx.showToast({
          title: '复制失败',
          icon: 'none'
        });
      }
    });
  },

  // 返回首页
  goToHome() {
    wx.reLaunch({
      url: '/pages/index/index'
    });
  }
});

